import { ref, type Ref } from 'vue'
import type { Message, Conversation, ProcessingTask, ResultPanel } from '../../types/home'
import { 
  getPanelTitle, 
  getPanelIcon, 
  getPanelIconBg, 
  getPanelStepBadge, 
  getPanelContent,
  scrollToElement 
} from '../../utils/home'

export function useChatProcessing(
  messages: Ref<Message[]>,
  processingTasks: Ref<ProcessingTask[]>,
  resultPanels: Ref<ResultPanel[]>,
  progress: Ref<number>
) {
  // 初始化处理任务
  const initializeProcessingTasks = (type: string) => {
    const taskConfig = {
      knowledge: [
        {
          id: 1,
          title: '1. 问题解析',
          description: '分析用户问题意图',
          icon: 'fas fa-search',
          details: {
            title: '问题解析流程',
            items: [
              '• 意图识别：确定用户询问的具体内容',
              '• 关键词提取：识别问题中的核心概念',
              '• 领域分类：判断问题所属的知识领域',
              '• 复杂度评估：分析问题的技术深度'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 2,
          title: '2. 知识检索',
          description: '搜索相关知识库',
          icon: 'fas fa-book',
          details: {
            title: '知识检索过程',
            items: [
              '• 文档匹配：查找相关技术文档',
              '• 内容筛选：过滤最相关的信息',
              '• 相关度排序：按匹配程度排序结果',
              '• 质量评估：验证信息的准确性'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 3,
          title: '3. 内容生成',
          description: '生成回答内容',
          icon: 'fas fa-magic',
          details: {
            title: '内容生成步骤',
            items: [
              '• 信息整合：综合多源信息',
              '• 逻辑组织：构建清晰的回答结构',
              '• 语言优化：确保表达流畅自然',
              '• 准确性检查：验证技术细节的正确性'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 4,
          title: '4. 结果优化',
          description: '优化最终回答',
          icon: 'fas fa-check-circle',
          details: {
            title: '结果优化流程',
            items: [
              '• 格式优化：调整段落结构和排版',
              '• 补充说明：添加必要的背景信息',
              '• 示例提供：增加具体的应用案例',
              '• 质量保证：确保回答的完整性和实用性'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        }
      ],
      data: [
        {
          id: 1,
          title: '1. 数据分析',
          description: '分析数据需求',
          icon: 'fas fa-chart-line',
          details: {
            title: '数据分析流程',
            items: [
              '• 需求理解：明确数据分析目标',
              '• 数据源识别：确定相关数据来源',
              '• 分析方法选择：选择合适的分析技术',
              '• 预期结果定义：设定分析输出标准'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 2,
          title: '2. 数据处理',
          description: '清洗和转换数据',
          icon: 'fas fa-database',
          details: {
            title: '数据处理步骤',
            items: [
              '• 数据收集：获取原始数据',
              '• 数据清洗：处理缺失值和异常值',
              '• 数据转换：标准化和格式化',
              '• 数据验证：确保数据质量'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 3,
          title: '3. 统计分析',
          description: '执行统计分析',
          icon: 'fas fa-calculator',
          details: {
            title: '统计分析过程',
            items: [
              '• 描述性统计：计算基本统计量',
              '• 推断统计：进行假设检验',
              '• 相关性分析：探索变量关系',
              '• 趋势分析：识别数据模式'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 4,
          title: '4. 可视化展示',
          description: '生成图表和报告',
          icon: 'fas fa-chart-bar',
          details: {
            title: '可视化流程',
            items: [
              '• 图表选择：选择合适的图表类型',
              '• 视觉设计：优化颜色和布局',
              '• 交互功能：添加用户交互元素',
              '• 报告生成：创建完整的分析报告'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        }
      ],
      image: [
        {
          id: 1,
          title: '1. 图像分析',
          description: '分析图像内容',
          icon: 'fas fa-image',
          details: {
            title: '图像分析流程',
            items: [
              '• 图像预处理：调整图像质量和尺寸',
              '• 特征提取：识别图像关键特征',
              '• 内容理解：分析图像语义信息',
              '• 场景识别：判断图像场景类型'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 2,
          title: '2. 对象检测',
          description: '识别图像中的对象',
          icon: 'fas fa-eye',
          details: {
            title: '对象检测步骤',
            items: [
              '• 目标定位：确定对象位置',
              '• 边界框生成：绘制对象边界',
              '• 置信度评估：评估检测准确性',
              '• 多对象处理：处理多个对象'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 3,
          title: '3. 图像处理',
          description: '处理和优化图像',
          icon: 'fas fa-palette',
          details: {
            title: '图像处理过程',
            items: [
              '• 滤镜应用：应用各种图像滤镜',
              '• 色彩调整：优化色彩平衡',
              '• 锐化处理：增强图像清晰度',
              '• 噪声消除：去除图像噪声'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 4,
          title: '4. 结果输出',
          description: '生成处理结果',
          icon: 'fas fa-file-export',
          details: {
            title: '结果输出流程',
            items: [
              '• 结果整理：组织处理结果',
              '• 格式转换：转换输出格式',
              '• 质量检查：验证输出质量',
              '• 文件生成：生成最终文件'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        }
      ],
      code: [
        {
          id: 1,
          title: '1. 需求分析',
          description: '分析代码需求',
          icon: 'fas fa-code',
          details: {
            title: '需求分析步骤',
            items: [
              '• 功能需求：确定需要实现的功能',
              '• 技术选型：选择合适的技术栈',
              '• 架构设计：设计代码结构',
              '• 接口定义：明确API接口'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 2,
          title: '2. 代码生成',
          description: '生成代码内容',
          icon: 'fas fa-keyboard',
          details: {
            title: '代码生成过程',
            items: [
              '• 逻辑设计：设计代码逻辑',
              '• 语法实现：编写具体代码',
              '• 错误处理：添加异常处理',
              '• 注释添加：编写代码注释'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 3,
          title: '3. 代码优化',
          description: '优化代码质量',
          icon: 'fas fa-tools',
          details: {
            title: '代码优化流程',
            items: [
              '• 性能优化：提升执行效率',
              '• 代码重构：改善代码结构',
              '• 内存优化：减少内存占用',
              '• 算法优化：改进算法效率'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        },
        {
          id: 4,
          title: '4. 测试验证',
          description: '测试代码功能',
          icon: 'fas fa-vial',
          details: {
            title: '测试验证步骤',
            items: [
              '• 单元测试：测试单个功能',
              '• 集成测试：测试整体功能',
              '• 性能测试：测试执行性能',
              '• 代码审查：检查代码质量'
            ]
          },
          showDetails: false,
          status: 'pending' as const
        }
      ]
    }

    processingTasks.value = taskConfig[type as keyof typeof taskConfig] || taskConfig.knowledge
  }

  // 添加结果面板
  const addResultPanel = (step: number, type: string) => {
    const panel: ResultPanel = {
      id: step,
      title: getPanelTitle(step),
      content: getPanelContent(step, type),
      icon: getPanelIcon(step),
      iconBg: getPanelIconBg(step),
      step: `步骤 ${step}`,
      stepBadge: getPanelStepBadge(step),
      timestamp: new Date(),
      active: false,
      visible: true
    }
    resultPanels.value.push(panel)
  }

  // 开始处理
  const startProcessing = async (type: string) => {
    const steps = [
      { step: 1, progress: 25, status: 'completed' as const },
      { step: 2, progress: 50, status: 'completed' as const },
      { step: 3, progress: 75, status: 'completed' as const },
      { step: 4, progress: 100, status: 'completed' as const }
    ]
    
    // 先将所有任务设置为处理中
    processingTasks.value.forEach((task: ProcessingTask) => {
      task.status = 'processing'
    })
    
    for (let i = 0; i < steps.length; i++) {
      const stepData = steps[i]
      
      // 动态更新进度
      const targetProgress = stepData.progress
      const currentProgress = progress.value
      const progressDiff = targetProgress - currentProgress
      
      // 分阶段更新进度，模拟真实的处理过程
      for (let p = 0; p < progressDiff; p += 5) {
        await new Promise(resolve => setTimeout(resolve, 100))
        progress.value = Math.min(currentProgress + p, targetProgress)
      }
      
      // 等待处理完成
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 更新任务状态
      const task = processingTasks.value.find((t: ProcessingTask) => t.id === stepData.step)
      if (task) {
        task.status = stepData.status
        // 如果任务完成，触发滚动到对应结果面板
        if (task.status === 'completed') {
          onTaskCompleted(task.id)
        }
      }
      
      // 确保进度达到目标值
      progress.value = targetProgress
      
      // 添加结果面板
      addResultPanel(stepData.step, type)
    }
  }

  // 处理任务点击
  const handleTaskClick = (task: ProcessingTask) => {
    if (task.status === 'completed') {
      // 显示/隐藏任务详情
      task.showDetails = !task.showDetails
      
      // 高亮对应的结果面板
      resultPanels.value.forEach((panel: ResultPanel) => {
        panel.active = panel.id === task.id
      })
      
      // 滚动到对应的结果面板
      scrollToResultPanel(task.id)
    }
  }

  // 处理结果面板点击
  const handleResultPanelClick = (panel: ResultPanel) => {
    // 高亮对应的处理任务
    const task = processingTasks.value.find((t: ProcessingTask) => t.id === panel.id)
    if (task && task.status === 'completed') {
      task.showDetails = true
      // 滚动到对应的处理任务，添加延时避免冲突
      setTimeout(() => {
        const taskElement = document.querySelector(`[data-task="${task.id}"]`)
        if (taskElement) {
          taskElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      }, 100)
    }
    
    // 高亮结果面板
    resultPanels.value.forEach((p: ResultPanel) => {
      p.active = p.id === panel.id
    })
  }

  // 滚动到指定的结果面板
  const scrollToResultPanel = (panelId: number) => {
    scrollToElement(`[data-result="${panelId}"]`, { behavior: 'smooth', block: 'start' })
    // 高亮对应的结果面板，但不触发循环调用
    resultPanels.value.forEach((panel: ResultPanel) => {
      panel.active = panel.id === panelId
    })
  }

  // 当处理任务完成时，自动滚动到对应的结果面板
  const onTaskCompleted = (taskId: number) => {
    const panel = resultPanels.value.find((p: ResultPanel) => p.id === taskId)
    if (panel) {
      scrollToResultPanel(taskId)
    }
  }

  // 重置处理状态
  const resetProcessing = () => {
    processingTasks.value = []
    resultPanels.value = []
    progress.value = 0
  }

  return {
    initializeProcessingTasks,
    startProcessing,
    handleTaskClick,
    handleResultPanelClick,
    resetProcessing
  }
}